import { getCurrentInstance, defineEmits, onUnmounted } from 'vue'

const scopeEventCache = {}

export function useScopeEvent() {
  const instance = getCurrentInstance()

  if (!scopeEventCache[instance.uid]) {
    scopeEventCache[instance.uid] = {}
  }

  onUnmounted(() => {
    delete scopeEventCache[instance.uid]
  })

  return {
    emit: (type: string, ...args) => {
      if (scopeEventCache[instance.uid][type]) {
        scopeEventCache[instance.uid][type].forEach(func => {
          try {
            func(...args)
          } catch { }
        })
      }
    },
    on: (type: string, func: (...args) => void) => {
      scopeEventCache[instance.uid][type] = scopeEventCache[instance.uid][type] || []
      scopeEventCache[instance.uid][type].push(func)
    }
  }
}